package com.walker.weixin.service.impl;

import com.walker.weixin.service.WxService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @Description:
 * @ProjectName: walker-step
 * @Package: com.walker.weixin.service.impl
 * @ClassName: WxServiceImpl
 * @Author: yangyl
 * @CreateDate: 2020/7/12 23:31
 */
@Service
public class WxServiceImpl implements WxService {

    protected static final Logger log = LoggerFactory.getLogger(WxServiceImpl.class);

    public static final String TOKEN = "IyuncheTestWang";


    /**
     * 验证签名
     *
     * @param signature 微信签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return
     */
    @Override
    public String check(String signature, String timestamp, String nonce, String echostr) {
        log.info("check signature: sign:{},timestamp:{},nonce:{},echostr:{}",signature,timestamp,nonce,echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            return "";
        }
        String[] arrays = {TOKEN, timestamp, nonce};
        Arrays.sort(arrays);
        StringBuilder stringBuilder = new StringBuilder();
        for (String tmp : arrays) {
            stringBuilder.append(tmp);
        }
        String mySignature = sha1(stringBuilder.toString());
        if(StringUtils.isNotBlank(mySignature) && StringUtils.equalsIgnoreCase(mySignature,signature)){
            log.info("check signature:true");
            return echostr;
        }else{
            log.info("check signature:false");

        }
        return null;
    }

    private String sha1(String data) {
        String sharData="";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("sha1");
            byte[] digests = messageDigest.digest(data.getBytes());
            char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e','f'};
            StringBuilder builder = new StringBuilder();
            for (byte digest : digests) {
                builder.append(chars[(digest >> 4) & 15]);
                builder.append(chars[digest & 15]);
            }
            sharData=builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sharData;
    }


}
